#include "loadinganimation.h"
#include <QLabel>
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
#include <QFont>
#include <QPoint>
#include <QHBoxLayout>

LoadingAnimation::LoadingAnimation(QWidget *parent)
    : QWidget{parent}
{
    this->m_layout = new QHBoxLayout(this);
    this->m_layout->setSpacing(10);
    this->m_layout->setAlignment(Qt::AlignCenter);

    this->m_animationGroup = new QSequentialAnimationGroup(this);

    for (int i = 0; i < 3; ++i)
    {
        QLabel *dot = new QLabel("●", this);
        dot->setObjectName("loadingDot");
        dot->setFont(QFont("Arial", 24));
        m_layout->addWidget(dot);
        m_dots.append(dot);
    }
    this->m_animationGroup->setLoopCount(-1);
}

void LoadingAnimation::start()
{
    m_animationGroup->clear(); // 清除所有旧的动画和暂停

    for (QLabel *dot : m_dots)
    {
        // 强制控件立即更新其几何位置
        dot->adjustSize();

        QPropertyAnimation *anim = new QPropertyAnimation(dot, "pos", this);
        anim->setDuration(300);
        anim->setEasingCurve(QEasingCurve::InOutQuad);

        QPoint startPos = dot->pos();
        // 如果起始位置有问题（比如控件还未完全布局好），给一个默认值
        if (startPos.isNull() == true)
        {
            startPos = QPoint(0,0);
        }

        anim->setStartValue(startPos);
        anim->setKeyValueAt(0.5, startPos + QPoint(0, -20));
        anim->setEndValue(startPos);

        m_animationGroup->addPause(150);
        m_animationGroup->addAnimation(anim);
    }

    m_animationGroup->start();

    return ;
}

void LoadingAnimation::stop()
{
    this->m_animationGroup->stop();
    return ;
}
